package com.kx.sms.controller;

import com.kx.base.dto.sms.SmsDTO;
import com.kx.base.result.R;
import com.kx.sms.service.SmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 处理短信的Controller
 *
 * @Author Sun
 * @Date 2021/7/19 19:26
 */
@RequestMapping("kx/sms")
@RestController
public class SmsController {

    @Autowired
    private SmsService smsService;

    /**
     * 发送短信
     */
    @PostMapping("send")
    public R send(@RequestBody SmsDTO smsDTO) {
        //1.接收其他子服务传递过来的手机号与验证码
        String phone = smsDTO.getPhone();
        String code = smsDTO.getCode();
        Integer typeId = smsDTO.getTypeId();
        //2.拼装成手机验证码的短信内容
        String smsBody = "【XX应用】：您的短信验证码为" + code + "。";
        //3、请求第三方短信平台，发送短信
        //http~请求，请求短信平台,这里简化为假请求
        //4、发送成功以后，把短信验证码存入数据库
        int result = smsService.saveSms(phone, code, typeId);
        if (result == 1) {
            return R.ok(200, "发送成功");
        } else {
            return R.error(500, "发送失败");
        }
    }

    /**
     * 检验短信
     */
    @PostMapping("check")
    public R check(@RequestBody SmsDTO smsDTO) {
        String phoneNo = smsDTO.getPhone();
        String code = smsDTO.getCode();
        Integer typeId = smsDTO.getTypeId();
        int result = smsService.checkSms(phoneNo, code, typeId);
        if (result == 1) {
            return R.ok(200,"短信验证码正确");
        }else if(result==0){
            return R.ok(501,"短信已经过期");
        }else {
            return R.ok(501,"短信验证码错误");
        }
    }
}
